from nicegui import ui, app, context
from starlette.routing import Route

from typing import Literal
from typing import cast
import 考试系统.数据交互层.GLOBA as GLOBA
from 考试系统.数据交互层.界面.base import base_page

from ex4nicegui.reactive import rxui
from ex4nicegui import to_ref, ref_computed, effect, effect_refreshable

from niceguiToolkit.layout import inject_layout_tool
# inject_layout_tool()


# -----------------------------------待完成函数


def get_classes():
    return ['人工智能', '计算机']


# ['小马哥', '小婕', '小刘']


def get_students_for_class(classname):
    if classname == '':
        return ['']
    dict = {
        '计算机': ['201', '202', '211', '212', '231', '232', '241', '242', '251', '252', '261', '262', '271', '272',
                   '281', '282', '301', '302', '311', '312', '331', '332', '341', '342', '351', '352', '361', '362',
                   '371', '372', '381', '382', '401', '402', '411', '412', '431', '432', '441', '442', '451', '452',
                   '461', '462', '471', '472', '481', '482'],
        '人工智能': ['303', '304', '313', '314', '323', '324', '333', '334', '343', '344', '353', '354', '363', '364',
                     '373', '374', '383', '384', '403', '404', '413', '414', '423', '424', '433', '434', '443', '444',
                     '453', '454', '463', '464', '473', '474', '483', '484', '501', '502', '511', '512']}
    return dict[classname]


def get_exam_for_class(classname):
    if classname == '':
        return ['null']
    return {
        'null':['null','null'],
        '人工智能': ['1', '2'],
        '计算机': ['1']}[classname]


def get_topic_for_exam(curr_class):
    if curr_class == '':
        return ['null']
    return {'人工智能': {'1': ['1', '2', '3'], '2': ['1', '3', '4']}, '计算机': {'1': ['1', '3', '5']}}[curr_class]


def up_classes(classname):
    pass


def up_stu_for_class(curr_class, stu_list):
    pass


def up_topic(topic_list):
    pass


def up_exam_for_class(curr_class, exam):
    pass


def view_topic():
    return {
        'null': ['null', 'null'],
        1: ["# 计算两个数的和", "编写一个程序，计算两个数的和。示例：2 + 3 = 5"],
        2: ["# 判断一个数是否是偶数", "编写一个程序，判断一个数是否是偶数。示例：2 是偶数，3 是奇数"],
        3: ["# 判断一个数是否是质数", "编写一个程序，判断一个数是否是质数。示例：2 是质数，4 不是质数"],
        4: ["# 计算列表中所有数字的和", "编写一个程序，计算列表中所有数字的和。示例：[1, 2, 3, 4, 5] 的和为 15"],
        5: ["# 反转一个字符串", "编写一个程序，反转一个字符串。示例：'hello' 反转后为 'olleh'"],
        6: ["# 检查一个字符串是否是另一个字符串的子序列",
            "编写一个程序，检查一个字符串是否是另一个字符串的子序列。示例：'he' 是 'hello' 的子序列"],
        7: ["# 生成斐波那契数列的前n个数字",
            "编写一个程序，生成斐波那契数列的前n个数字。示例：前10个斐波那契数为 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]"],
        8: ["# 判断一个数是否是另一个数的倍数",
            "编写一个程序，判断一个数是否是另一个数的倍数。示例：6 是 2 的倍数，但不是 3 的倍数"],
        9: ["# 将一个温度从摄氏度转换为华氏度",
            "编写一个程序，将一个温度从摄氏度转换为华氏度。示例：25摄氏度转换为华氏度为 77.00"],
        10: ["# 找到列表中的最大和最小元素",
             "编写一个程序，找到列表中的最大和最小元素。示例：[5, 2, 9, 1, 5] 的最大元素为 9，最小元素为 1"]
    }


# -----------------------------------变量区


class_name = ""

claes = to_ref(get_classes())
students_for_class = to_ref([''])
exams_for_class = to_ref({})
topics = to_ref(view_topic())
search_topic = to_ref('')
search_stu = to_ref('')
current_class = to_ref("")
topic_for_exam = to_ref({})


@ref_computed
def students():
    return [stu for stu in students_for_class.value if stu.find(search_stu.value) >= 0]


@ref_computed
def exams():
    return [stu for stu in exams_for_class.value if stu.find(search_stu.value) >= 0]


@ref_computed
def exams_topics():
    return list(topic_for_exam.value.items())


@ref_computed
def topic_list():
    new_dict = {}
    for key, value in topics.value.items():
        if value[0].find(search_topic.value) >= 0:
            new_dict[key] = value
    if search_topic.value != '':
        print(new_dict)
    return list(new_dict.items())


# @ref_computed
# def topic_result():
#     return str(topiclist.value)


def class_name_change(e):
    global class_name
    class_name = e.value


def up_new_class(class_name):
    claes.value.append(class_name)
    claes.value = claes.value
    up_classes(claes.value)


def set_students(classname):
    students_for_class.value = get_students_for_class(classname)


def add_stu(id):
    students_for_class.value.append(id)
    students_for_class.value = students_for_class.value
    students_for_class.value = sorted(students_for_class.value)
    up_stu_for_class(current_class, students_for_class.value)


def delete_stu(id):
    students_for_class.value = [num for num in students_for_class.value if num != str(id)]
    students_for_class.value = sorted(students_for_class.value)
    up_stu_for_class(current_class, students)


def add_topic(title, content):
    topics.value[len(topics.value) + 1] = [title, content]
    topics.value = topics.value
    up_topic(topics.value)


def delete_topic(id):
    new_dict = {}
    i = 1
    one = 1
    for key, value in topics.value.items():
        if i == id and one:
            print('删除')
            one = 0
            continue
        new_dict[i] = value
        i += 1
    topics.value = new_dict
    topics.value = topics.value
    up_topic(topics.value)
    # 输出结果
    print(topics.value)


def change_topic(id, title, content):
    if (title != ''):
        topics.value[id][0] = title
    if content != '':
        topics.value[id][1] = content
    print(id, ";", title, ";", content)
    topics.value = topics.value
    up_topic(topics.value)


topic_title = to_ref('')
topic_content = to_ref('')

# -----------------------------------界面

with ui.dialog() as dialog_creat_class, ui.card():
    ui.label('创建班级')
    ui.input('班级名', on_change=class_name_change)
    ui.button('Done', on_click=lambda: {ui.notify(f'{class_name}班级创建成功'), up_new_class(class_name),
                                        dialog_creat_class.close()} if not class_name == '' else ui.notify(
        '班级名不能为空'))

with ui.dialog() as dialog_creat_topic, ui.card():
    ui.label('创建题目')
    rxui.input('题目标题', value=topic_title)
    rxui.textarea('题目内容', value=topic_content)
    ui.button('Done', on_click=lambda: {ui.notify(f'{topic_title.value}题目创建成功'),
                                        add_topic(topic_title.value, topic_content.value),
                                        dialog_creat_topic.close()} if not topic_title.value == '' and not topic_content.value == '' else ui.notify(
        '题目名或内容不能为空'))

creat_stu = to_ref('')
with ui.dialog() as dialog_creat_stu,ui.card():
    ui.label('添加学生')
    rxui.input('学生名', value=creat_stu)
    ui.button('Done', on_click=lambda: {ui.notify(f'{creat_stu.value}学生创建成功'), add_stu(creat_stu.value),
                                        dialog_creat_stu.close()} if not creat_stu.value == '' else ui.notify(
        '学生名不能为空'))

_current_key = 0


def _dialog_change_topic(key):
    global _current_key
    _current_key = key
    print('key:', key)
    dialog_change_topic.open()


with ui.dialog() as dialog_change_topic, ui.card():
    ui.label('改变题目')
    rxui.input('题目标题', value=topic_title)
    rxui.textarea('题目内容', value=topic_content)
    ui.button('Done', on_click=lambda: {ui.notify(f'{class_name}题目改变成功'),
                                        change_topic(_current_key, topic_title.value, topic_content.value),
                                        dialog_change_topic.close()} if not topic_title.value == '' or not topic_content.value == '' else ui.notify(
        '题目名或内容不能为空'))

@ui.page('/teacher')
def teacher_page():
    base = base_page()
    with base.replace('header'):
        with ui.tabs().style("align-self:center;width:auto").classes('w-full') as tabs:
            def close_class():
                tabs_panel.set_visibility(True)
                card_class.set_visibility(False)

            ui.button('主页', on_click=lambda: {close_class(), tabs.set_value('initial')})

            with ui.element('q-btn-dropdown').props('auto-close stretch flat label="班级"').on('click', lambda: {
                class_menu.open()}):
                ui.button('创建班级', on_click=lambda: {dialog_creat_class.open(), close_class()})
                with ui.button('选择班级'):
                    with ui.menu() as class_menu:
                        ui.menu_item('关闭', on_click=lambda: {close_class(), tabs.set_value('initial')})

                        @effect_refreshable  # 创建一个动态刷新的函数
                        def _():
                            for claes_name in claes.value:
                                def on_click(claes_name=claes_name):
                                    tabs_panel.set_visibility(False)
                                    card_class.set_visibility(True)
                                    current_class.value = claes_name
                                    ui.notify(current_class.value)
                                    students_for_class.value = get_students_for_class(current_class.value)
                                    exams_for_class.value = get_exam_for_class(current_class.value)
                                    topic_for_exam.value = get_topic_for_exam(current_class.value)
                                    class_menu.close()

                                ui.menu_item(
                                    claes_name,
                                    auto_close=False,
                                    on_click=on_click,
                                )
            ui.button('题库', on_click=lambda: {print(topics.value), tabs.set_value('topic'), close_class()})

    ###-----------------主体----------------###
    with base.replace('body'):
        with ui.tab_panels(tabs, value='initial').classes('w-full') as tabs_panel:
            with ui.tab_panel('initial'):
                with ui.card().classes('w-full h-[35rem]'):
                    ui.label('这是主页面')
                    # GLOBA.image()
            with ui.tab_panel('topic'):
                with ui.row():
                    with ui.row():
                        ui.button('增加题目', on_click=lambda: dialog_creat_topic.open())
                    with ui.row():
                        rxui.input('题目搜索', value=search_topic, placeholder='输入题目标题搜索题目').classes(
                            'w-[20rem] self-center').props('outlined clearable debounce="500"')

                topic_pagination = rxui.use_pagination(topic_list, page_size=12)
                with ui.grid(columns=4):
                    @effect_refreshable
                    def _():
                        for l in topic_pagination.current_source.value:
                            with ui.card().classes('w-[15rem] h-[7rem]'):
                                with ui.grid(columns=2):
                                    ui.label('id'), ui.label(l[0])
                                    ui.label('title'), ui.label(l[1][0])
                                ui.tooltip(l[1][1])
                                with ui.context_menu():
                                    ui.menu_item('改变题目', on_click=lambda e, i=l: {print('l[0]:', i[0]),
                                                                                      _dialog_change_topic(i[0])})
                                    ui.menu_item('删除题目', on_click=lambda e, i=l: {delete_topic(i[0]),
                                                                                      ui.notify(f'{i[0]}删除成功')})

                topic_pagination.create_q_pagination().classes('w-full')

        with ui.card().classes('w-full h-[35rem]') as card_class:
            @effect_refreshable  # 创建一个动态刷新的函数
            def _():
                with ui.tab_panels(value=current_class.value):
                    for class_name in claes.value:
                        with ui.tab_panel(class_name):

                            with ui.row():
                                rxui.label('班级: ' + current_class.value)
                                change_grid_stu_page = change_grid_button = ui.button('切换为试卷界面')
                            with ui.row():
                                with ui.row():
                                    add_stu_button = ui.button('增加学生',
                                                               on_click=lambda: dialog_creat_stu.open())
                                with ui.row():
                                    rxui.input('学生搜索', value=search_stu,
                                               placeholder='输入学号搜索学生').classes(
                                        'w-[20rem] self-center').props('outlined clearable debounce="500"')

                            exam_pagination = rxui.use_pagination(exams, page_size=4)
                            with ui.grid(columns=2).classes('w-full h-full') as exam_grid:

                                @effect_refreshable
                                def _(exam_pagination=exam_pagination):
                                    for l in exam_pagination.current_source.value:
                                        with ui.card().classes('w-[20rem] h-[7rem]'):
                                            with ui.row():
                                                ui.label('考试ID:' + l)
                                                with ui.column():
                                                    @effect_refreshable
                                                    def _():
                                                        if l == '' or l == 'null' or l not in topic_for_exam.value:
                                                            return
                                                        for topic_id in topic_for_exam.value[l]:
                                                            ui.label(topics.value[int(topic_id)][0])
                                            with ui.context_menu():
                                                ui.menu_item('改变题目')
                                                ui.menu_item('删除题目')
                                                ui.menu_item('删除试卷')
                            with ui.row().classes('w-full'):
                                exam_pagination.create_q_pagination().classes(' flex-center')
                            exam_grid.visible = False

                            stu_pagination = rxui.use_pagination(students, page_size=12)  # 只有最后一个班级才能分页,舍弃/改好了,继续用!!!
                            with ui.grid(columns=4) as stu_grid:
                                @effect_refreshable
                                def _(stu_pagination=stu_pagination):
                                    for l in stu_pagination.current_source.value:
                                        # for l in students.value:
                                        with ui.card().classes('w-[15rem] h-[7rem]'):
                                            ui.label(l)
                                            with ui.context_menu():
                                                ui.menu_item('删除学生', on_click=lambda e, i=l: {delete_stu(i)})

                                stu_pagination.create_q_pagination().classes('w-full')

                            stu_grid.visible = True

                            # 切换到试卷界面
                            def change_grid(exam_grid=exam_grid, stu_grid=stu_grid,add_stu_button=add_stu_button):
                                ui.notify(current_class.value)
                                if stu_grid.visible == True:
                                    change_grid_button.set_text('切换为试卷页面')
                                    add_stu_button.visible = True
                                else:
                                    change_grid_button.set_text('切换为学生页面')
                                    add_stu_button.visible = False
                                exam_grid.visible = not exam_grid.visible
                                stu_grid.visible = not stu_grid.visible

                            change_grid_stu_page.on('click', change_grid)


teacher_page()

ui.run(reload=True)
